package com.jiepos.mpos.core.intercept;

import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.jiepos.mpos.common.constant.SystemConstant;
import com.jiepos.mpos.core.util.GlobalUtils;
import com.jiepos.mpos.core.util.StringUtils;

/**
 * 
 * 描述: 事件拦截器,校验权限
 *  模块: 通用平台
 * 
 * @author 娄伟峰
 * @version 1.0
 * @since 2012-5-22 上午10:57:56
 * @history（历次修订内容、修订人、修订时间等）
 */
public class EventInterceptor extends HandlerInterceptorAdapter {	
	
	public final Logger log = LoggerFactory.getLogger(getClass());

	/**
	 * 这个方法在业务处理器处理请求之前被调用，在该方法中对用户请求request进行处理。
	 * 如果程序员决定该拦截器对请求进行拦截处理后还要调用其他的拦截器，或者是业务处理器去进行处理，则返回true；
	 * 如果程序员决定不需要再调用其他的组件去处理请求，则返回false。
	 */
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String postUri = request.getRequestURI();
 
			//  保存后台操作日志数据
	 
			log.debug("preHandle : "+postUri+"  ip : "+this.getIpAddr(request));
			if (postUri.indexOf("/loginSystem.do") > -1 || postUri.indexOf("/logoutSystem.do") > -1   ) {
				return true;
			}		 
			if( !postUri.contains("billResult.do") && !postUri.contains("cmbcBillResult.do")){
				return true;
			}
			
			String loginUser = String.valueOf(request.getSession().getAttribute(SystemConstant.SESSION_LOGIN_USER));
			if(StringUtils.isBlank(loginUser)){
				return false;
			}
		//	log.info("用户账号为 : "+loginUser +"  用户IP为 :"+this.getIpAddr(request) + " postUri: "+postUri +" queryString:"+request.getQueryString());
			return this.check(request, response, handler);
		 
		 

	}
	
	public boolean check(HttpServletRequest request, HttpServletResponse response, Object handler)  throws Exception{
		
		String postUri = request.getRequestURI();
		Enumeration rnames=request.getParameterNames();
		String loginUser = String.valueOf(request.getSession().getAttribute(SystemConstant.SESSION_LOGIN_USER));
		List tempList = (List) request.getSession().getAttribute(SystemConstant.SESSION_AUTH_LIST);
 
		String str = "";
		for (Enumeration e = rnames ; e.hasMoreElements() ;) {
		         String thisName=e.nextElement().toString();
		        String thisValue=request.getParameter(thisName);
		        str = str+";"+ thisName+"="+thisValue;
		}
		log.info("用户账号为 : "+loginUser +"  用户IP为 :"+this.getIpAddr(request) + " postUri: "+postUri +" queryString:"+request.getQueryString()+" formdata:"+str);
		if(!postUri.contains("http") && !postUri.contains("billResult.do") && !postUri.contains("cmbcBillResult.do")){	 
			if(!tempList.contains(postUri.replace("/"+GlobalUtils.getAppName(), "")) ){
				response.sendRedirect(request.getContextPath()+"/module/common/noauth.jsp");
				return false;
			}
		 
		}
		return true;
	}
	 

    /**
     * 通过HttpServletRequest返回IP地址
     * @param request HttpServletRequest
     * @return ip String
     * @throws Exception
     */
    public String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
	/**
	 * 这个方法在业务处理器处理完请求后，但是DispatcherServlet向客户端返回请求前被调用，在该方法中对用户请求request进行处理。
	 */
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

	}

	/**
	 * 这个方法在DispatcherServlet完全处理完请求后被调用，可以在该方法中进行一些资源清理的操作
	 */
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {

	}

}
